package com.joysuch.wwyt.core.support;

import cn.zlg.common.util.CollectionUtils;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseLoginAccountDao;
import com.joysuch.wwyt.core.repository.BaseRoleUserLoginRoleDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.security.ShiroUser;
import com.joysuch.wwyt.core.service.BaseRoleDataAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author : pp
 * @date : Created in 2021/4/17 22:08
 */
@Slf4j
@Component
public class AuthorityScopeComponent {
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BaseLoginAccountDao baseLoginAccountDao;
    @Autowired
    private BaseRoleDataAuthService roleDataAuthService;
    @Autowired
    private BaseRoleUserLoginRoleDao baseRoleUserLoginRoleDao;

    public Set<Long> authorityUserIdData() {

        // 获取当前登录的用户信息
        Subject subject = SecurityUtils.getSubject();
        ShiroUser user = (ShiroUser) subject.getPrincipal();
        BaseUser baseUser = baseLoginAccountDao.findById(user.getId()).getBaseUser();
        if (baseUser == null) {
            throw new RuntimeException("登录用户不存在");
        }
        List<Long> roleIds = baseRoleUserLoginRoleDao.selectRoleIdsByUserId(baseUser.getId());
        Set<Long> summaryUserIds = new HashSet<>();
        roleIds.forEach(role->{
            if (role != null) {
                Set<Long> departEmpIds = roleDataAuthService.getSummaryUserIds(role, baseUser.getDepartId());
                //通过角色id查询对应的数据权限
                Set<Long> userIds = roleDataAuthService.getEmpAuthUserIds(role, baseUser.getId());
                summaryUserIds.addAll(departEmpIds);
                summaryUserIds.addAll(userIds);
            }
        });
        if (CollectionUtils.isNotEmpty(summaryUserIds)){
            return summaryUserIds;
        }
        return null;
    }
}
